#include "addfriendsearch.h"
#include "ui_addfriendsearch.h"
#include "user.h"
#include "showinfo.h"
#include <QHostAddress>
#include <QMessageBox>

addfriendsearch::addfriendsearch(QWidget *parent,user userSelf) :
    QDialog(parent),
    ui(new Ui::addfriendsearch)
{
    ui->setupUi(this);
    this->userSelf = userSelf;
    groupButton1=new QButtonGroup(this);
    groupButton1->addButton(ui->query_name,0);
    groupButton1->addButton(ui->query_id,1);
    connect(ui->query_name,SIGNAL(clicked(bool)),this,SLOT(slots_queryType()));
    connect(ui->query_id,SIGNAL(clicked(bool)),this,SLOT(slots_queryType()));
}

void addfriendsearch::on_btn_send_addfriendsearch_clicked()
{
    //Sender创建
    UserBrief Sender;//创造一个UserBrief
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
    QString senderToken = userSelf.getUserPassword();
    QString receiverInfo=ui->receiverInfo->text();
    QString idOrName=this->querytype;//1为id 0为name 待radio完成，默认为2有问题
    QString resourcePath = ":/asset/config/config.json";
    QFile jsonFile(resourcePath);
    if (jsonFile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
    QByteArray jsonData = jsonFile.readAll();
    // 将 JSON 数据转换为 QVariant 对象
    QJsonParseError error;
    QJsonObject result = QJsonDocument::fromJson(jsonData, &error).object();
    QJsonObject jsonUrl = QJsonDocument::fromJson(jsonData).object();
    qDebug() << "url :" << jsonUrl;
    jsonFile.close();
    QVariantMap urlVariantMap = jsonUrl.toVariantMap();
    QMap urlMap = urlVariantMap.value("server").toMap();
    host = urlMap.value("host").toString();
    port = urlMap.value("port").toString();
    }
    QNetworkRequest request(QUrl("http://"+host+':'+port+"/slimarveous/search_friend"));//连接http协议
    QJsonObject json2;
    //应该有radio button未实现
    if(idOrName=="1")//如果为id
    {
        json2={
            {"search_type_code",1},
            {"id",receiverInfo.toInt()},
            {"username",""},//username暂时为空
            {"self_id", Sender.id.toInt()},
            {"token",senderToken}
        };
    }
    else if(idOrName=="0")//如果为name
    {
        json2={
            {"search_type_code",2},
            {"id",0},//id暂时为空
            {"username",receiverInfo},
            {"self_id", Sender.id.toInt()},
            {"token",senderToken}
        };
    }
    else
    {
        this->close();
        QMessageBox::information(this,"填写有误","您未选择查询的是id还是名称，请重新填写！");
        addfriendsearch *afs=new addfriendsearch(nullptr,userSelf);
        afs->show();
    }
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json2");//创建回复连接
    QJsonDocument doc(json2);
    QByteArray data = doc.toJson(QJsonDocument::Compact);
    qDebug()<<data;
    QNetworkReply *reply = manager.post(request, data);
    //response为弹窗形式
    connect(reply, &QNetworkReply::finished, [=]()
    {
        if (reply->error() == QNetworkReply::NoError)
        {
            // 读取响应数据
            QByteArray dataReply = reply->readAll();
            // 将 JSON 数据转换为 QVariant 对象
            QJsonParseError error;
            QJsonObject result = QJsonDocument::fromJson(dataReply, &error).object();
            // 处理 JSON 数据
            if(error.error == QJsonParseError::NoError)
            {
                QVariantMap resultMap = result.toVariantMap();
                //提取状态码
                QVariant status_code = resultMap.value("status_code");
                status_code.toString();
                if(status_code == "2")
                {
                    QVariant is_friend_code = resultMap.value("is_friend_code");

                    is_friend_code.toString();
                    if(is_friend_code=="0")
                    {
                        QMessageBox::information(this,"查询结果","你们还不是好友，速去添加~");
                        showinfo *si=new showinfo(nullptr,userSelf,resultMap);
                        si->show();
                    }
                    else
                        QMessageBox::information(this,"查询结果","你们已经是好友哩~");
                }
                else if(status_code == "1")
                    QMessageBox::information(this,"查询失败","不存在该用户！");
                //服务器出问题
                else
                    QMessageBox::information(this,"查询失败","好像哪里出了问题呢？肯定不是服务器的问题！");

            }
        }
        else
            qDebug()<<"error";
        reply->deleteLater();
    });
    this->close();
}

void addfriendsearch::on_btn_clear_addfriendsearch_clicked()
{
    ui->receiverInfo->clear();
}

addfriendsearch::~addfriendsearch()
{
    delete ui;
}

void addfriendsearch::slots_queryType()//查询按钮，0为名称，1为id
{
    if(groupButton1->checkedId()==0)
        querytype="0";
    else
        querytype="1";
}
